<template>
  <div class="edit-container">
    <!-- 返回箭头 -->
    <el-button @click="goBack" class="back-btn">
      <el-icon><ArrowLeft /></el-icon>
    </el-button>

    <!-- 标题 -->
    <h2 class="page-title">{{ route.query.isAdd === 'true' ? '新增知识点' : '编辑知识点' }}</h2>

    <!-- 编辑表单 -->
    <el-form :model="editForm" label-width="120px" class="edit-form">
      <el-form-item label="知识点名称">
        <el-input v-model="editForm.name" />
      </el-form-item>

      <el-form-item label="教材版本">
        <el-input v-model="editForm.textBook" />
      </el-form-item>

      <!-- 新增：简要介绍（富文本） -->
      <el-form-item label="简要介绍">
        <el-input v-model="editForm.description" height="200px" />
      </el-form-item>


         <el-form-item label="年级">
            <el-select
              v-model="editForm.gradeId"
              placeholder="请选择年级"
              style="width: 100%"
            >
              <el-option
                v-for="grade in gradeOptions"
                :key="grade.id"
                :label="grade.name"
                :value="grade.id"
              />
            </el-select>
          </el-form-item>

   
       <el-form-item label="科目">
            <el-select
              v-model="editForm.subjectId"
              placeholder="请选择科目"
              style="width: 100%"
            >
              <el-option
                v-for="subject in subjectOptions"
                :key="subject.id"
                :label="subject.name"
                :value="subject.id"
              />
            </el-select>
          </el-form-item>
 

      <!-- 新增：视频讲解 -->
      <el-form-item label="视频讲解">
        <el-upload
          class="video-upload"
          action="#"
          :on-success="handleVideoUpload"
          :file-list="videoFileList"
          accept="video/*"
          :limit="1"
        >
          <el-button type="primary">上传视频</el-button>
        </el-upload>
      </el-form-item>

      <!-- 新增：视频说明（富文本） -->
      <el-form-item label="视频说明">
        <el-input v-model="editForm.videoDescription" height="200px" />
      </el-form-item>

      <!-- 新增：关联知识点（树形组件） -->
      <el-form-item label="关联知识点">
        <connect-knowledges
          ref="knowledgeTreeRef"
          :data="treeKnowledgeData"
          :self="editForm"
          :disabled="!isEdit"
        />
      </el-form-item>


      <el-form-item label="难度">
        <el-select v-model="editForm.difficulty"
        placeholder="请选择难度" style="width: 100%">
          <el-option 
            label="简单题" 
            :value="0" 
          />
          <el-option 
            label="中等题" 
            :value="1" 
          />
          <el-option 
            label="难题" 
            :value="2" 
          />
        </el-select>
      </el-form-item>

     
      <el-form-item label="标签名">
        <el-select v-model="editForm.tagNames" multiple
        placeholder="请选择标签名" style="width: 100%">
          <el-option 
            label="测试" 
            value="测试" 
          />
          <el-option 
            label="易错题" 
            value="易错题" 
          />
          <el-option 
            label="难点" 
            value="难点" 
          />
        </el-select>
      </el-form-item>


     <el-form-item label="前置知识点">
        <el-select v-model="editForm.prerequisiteKnowledgeIds" 
         multiple placeholder="请选择前置知识点" style="width: 100%">
          <el-option 
            v-for="item in flattenKnowledgeList" 
            :key="item.id" 
            :label="item.name" 
            :value="item.id" 
          />
        </el-select>
      </el-form-item>


      <el-form-item label="版本">
         <el-select v-model="editForm.version" placeholder="请选择版本" style="width: 100%">
          <el-option label="数学" value="1" />
          <el-option label="英语" value="2" />
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions" v-if="!route.query.isDetail">
      <el-button @click="goBack">取消</el-button>
      <el-button type="primary" @click="submitEdit">提交</el-button>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ElUpload, ElSelect, ElOption, ElCascader } from 'element-plus'
import ConnectKnowledges from './connectKnowledges.vue'
import { ArrowLeft } from '@element-plus/icons-vue'

const subjectOptions = ref(knowledgesApi.subjects);
const gradeOptions = ref(knowledgesApi.grades);
const router = useRouter()
const route = useRoute()
import * as knowledgesApi from "@/api/knowledges.js";
// 编辑表单数据
const editForm = reactive({
  name: '',
  tagNames: [],
  children: [],
  subjectId: 1,
  gradeId: 1,
  version: 1,
  textBook: '', // 补充教材版本字段
  // 新增字段
  description: '',
  detailedDescription: '',
  videoUrl: '',
  videoDescription: '',
  relatedKnowledgeIds: [],
  prerequisiteKnowledgeIds: [], // 前置知识点ID数组
  difficulty: 0 // 难度等级（0-简单题，1-中等题，2-难题）
})





let flattenKnowledgeList = ref([]) // 扁平化后的知识点列表 --- 也可以靠后端获取


// 获取所有知识点（包括子知识点）

function getFlattenKnowledges() {
  // knowledgeApi.getKnowledgeList().then(res => {
  //   if (res.code === 200) {
  //     flattenKnowledgeList.value = res.data || []
  //   }
  // })

}


// 地区选项（固定安徽-合肥）
const versionOptions = ref([{
  value: '安徽',
  label: '安徽',
  children: [{
    value: '合肥',
    label: '合肥'
  }]
}]);



// 视频上传相关
const videoFileList = ref([])
const handleVideoUpload = (response, file, fileList) => {
  // 模拟视频上传成功
  editForm.videoUrl = URL.createObjectURL(file.raw)
  videoFileList.value = fileList
}

// 树形组件引用
const knowledgeTreeRef = ref(null)

// 所有知识点（用于关联知识点树形组件）
const allKnowledges = ref([])
const currentKnowledgeId = ref(0)

// 格式化树形组件数据
const treeKnowledgeData = computed(() => {
  // 这里假设 allKnowledges 已经是树形结构
  // 如果不是，需要进行转换
  return allKnowledges.value.map(item => ({
    ...item,
    // 确保有 children 属性
    children: item.children || []
  }))
})

// 处理树形组件选中事件
const handleKnowledgeCheck = (checkedKeys) => {
  editForm.relatedKnowledgeIds = checkedKeys
}


const isEdit = computed(() => {
  if (route.query.isDetail === 'true') {
    return false;
  }
  if (route.query.isAdd === 'true') {
    return false;
  }
  return true;
})

// 加载知识点详情或初始化新增表单
onMounted(async () => {

  const isAdd = route.query.isAdd === 'true'
  if (isAdd) {
    // 新增模式：初始化表单
    currentKnowledgeId.value = 0
    editForm.name = ''
    editForm.tagNames = [];
    editForm.gradeId = 1
    editForm.subjectId = 1
    editForm.version = 1
    editForm.textBook = ''
    editForm.description = ''
    editForm.detailedDescription = ''
    editForm.videoUrl = ''
    editForm.videoDescription = ''
    editForm.relatedKnowledgeIds = []
    editForm.prerequisiteKnowledgeIds = [] // 前置知识点ID数组
    editForm.difficulty = 0 // 难度等级（0-简单题，1-中等题，2-难题）
    
    // 加载所有知识点用于关联选择
    allKnowledges.value = []
  } else {
    // 编辑模式：加载现有知识点
    const knowledgeId = route.query.id
    currentKnowledgeId.value = knowledgeId
    const res = await knowledgesApi.getKnowledgePointById(knowledgeId)
    if (res.code == 200) {
      const target = res.data;
      editForm.id = target.id;
      editForm.name = target.name
      editForm.tagNames = target.tagNames || []
      editForm.gradeId = target.gradeId
      editForm.subjectId = target.subjectId
      editForm.version = target.version || 1
      editForm.textBook = target.textBook || ''
      editForm.description = target.description || ''
      editForm.detailedDescription = target.detailedDescription || ''
      editForm.videoUrl = target.videoUrl || ''
      editForm.videoDescription = target.videoDescription || ''
      editForm.relatedKnowledgeIds = target.relatedKnowledgeIds || []

      editForm.prerequisiteKnowledgeIds = target.prerequisiteKnowledgeIds || [] // 前置知识点ID数组
      editForm.difficulty = target.difficulty || 0 // 难度等级（0-简单题，1-中等题，2-难题）

      allKnowledges.value = target.children;
      // 设置树形组件的选中项
      setTimeout(() => {
        if (knowledgeTreeRef.value) {
          knowledgeTreeRef.value.setCheckedKeys(editForm.relatedKnowledgeIds)
        }
      }, 0)
    } else {
      ElMessage.error('知识点不存在')
      router.back()
    }
  }
})

// 返回列表页
const goBack = () => {
  router.back()
}

// 提交编辑或新增
const submitEdit = async () => {
  const isAdd = route.query.isAdd === 'true'

  if (isAdd) {
    // 新增知识点
    const res = await knowledgesApi.addOrUpdateKnowledgePoint({
      ...editForm
    })
    if (res.code == 200) {
      ElMessage.success('知识点新增成功')
    } else {
      return ElMessage.error('知识点新增失败')
    }
  
  } else {
  
    const res = await knowledgesApi.addOrUpdateKnowledgePoint({
      id: currentKnowledgeId.value,
      ...editForm,
      children: knowledgeTreeRef.value.treeData
    })
    if (res.code == 200) {
      ElMessage.success('知识点更新成功')
    } else {
      return ElMessage.error('知识点更新失败')
    }
  }
  router.back()
}


onMounted(() => {
  getFlattenKnowledges()
})

</script>

<style scoped lang="scss">
.edit-container {
  padding: 24px;
  
  .back-btn {
    margin-bottom: 16px;
  }

  .page-title {
    margin-bottom: 32px;
    font-size: 20px;
    font-weight: bold;
    color: #333;
  }

  .edit-form {
    max-width: 600px;
    margin: 0 auto;
  }

  .form-actions {
    margin-top: 40px;
    text-align: center;
    
    .el-button + .el-button {
      margin-left: 24px;
    }
  }
}

// 新增样式
.el-textversion {
  margin-bottom: 20px;
}

.video-upload {
  margin-bottom: 20px;
}
</style>